import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="chooseDirectory()">选择一个文件夹</button>
    <br>
    <div *ngIf="!fileList || fileList.length === 0">没有文件</div>
    <table *ngIf="fileList && fileList.length > 0" border="1">
      <tr>
        <th>类型</th>
        <th>名称</th>
        <th>操作</th>
      </tr>
      <tr *ngFor="let item of fileList">
        <td>{{item.type}}</td>
        <td>{{item.key}}</td>
        <td>
          <button (click)="readFile(item)">读取文件</button>
        </td>
      </tr>
    </table>

    <textarea [(ngModel)]="content"></textarea>
    <br>
    <button (click)="updateFile()">修改文件</button>
  `,
  styles: [],
})
export class AppComponent {
  win = window as any;
  dirHandle: any;
  fileList: any[] = [];

  current: any;
  content: any;

  async chooseDirectory() {
    this.dirHandle = await this.win.showDirectoryPicker();
    console.log('dirHandle', this.dirHandle);
    this.fileList = [];
    for await (const [key, value] of this.dirHandle.entries()) {
      const file = {
        key,
        value,
        type: value.kind,
      };
      console.log('file', file);
      this.fileList.push(file);
    }
  }

  async readFile(item: any) {
    this.current = item;
    console.log('readFile', item);
    const fileData = await item.value.getFile();
    console.log('fileData', fileData);
    this.content = await fileData.text();
    console.log('fileData', this.content);
  }

  async updateFile() {
    let writable = await this.current.value.createWritable();
    await writable.write(this.content);
    await writable.close();
  }
}
